package ajax;

import helpers.StringHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;

import models.UserModel;

import data.UserData;
import forms.UserForm;

public class RegisterAjaxServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		HttpSession session = request.getSession();
		
		UserData userData = new UserData();
		UserModel user = new UserModel();
		UserForm userForm = new UserForm();
		
		TreeMap forms = (TreeMap) userForm.checkValid(request, user);
		user = (UserModel) forms.get("user");
		TreeMap check = (TreeMap) forms.get("checkValid");
		
		if (check.size() == 0) {
			user.setPassword(StringHelper.md5(user.getPassword()));
			user.setStatus(2);
			userData.insert(user);
			
			
			//Save login to session
			session.setAttribute("user_logged_in", user);
			check.put("success", true);
		} else {
			check.put("success", false);
		}
		
		String json = new Gson().toJson(check);
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json);
		
	}
}
